package org.esti.service.impl;

import org.esti.model.User;
import org.esti.model.dao.UserDAO;
import org.esti.model.exceptions.UserAlreadyExistException;
import org.esti.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Artem Loginov (logart)
 */

/**
 * {@inheritDoc}
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO dao;

    /**
     * {@inheritDoc}
     */
    @Override
    public User createUser(User user) {
        if (!dao.isUserExist(user)) {
            return dao.add(user);
        } else {
            throw new UserAlreadyExistException("user with login " + user.getLogin() + " already exist");
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isUserExist(User user) {
        return dao.isUserExist(user);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public User getUserByLogin(String login) {
        return dao.getByLogin(login);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public User updateUser(
            String login,
            String name,
            String middleName,
            String surname,
            Date birthday) {

        User user = getUserByLogin(login);

        user.setName(name);
        user.setMiddleName(middleName);
        user.setSurname(surname);
        user.setBirthday(birthday);


        //TODO validation.

        /***
         ***
         *** This validation code does not work and i don't know why.
         *
         ***/
//
////        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
////        Validator validator = validatorFactory.getValidator();
//
//        LOGGER.log(Level.INFO, "validator: '" + validator + '\n');
//
//        Set<ConstraintViolation<User>> violations = validator.validate(user);
//
//        for (ConstraintViolation<User> violation : violations) {
//            String propertyPath = violation.getPropertyPath().toString();
//            String message = violation.getMessage();
//            LOGGER.log(Level.INFO, "invalid value for: '" + propertyPath + "': " + message+'\n');
//        }
//
//        if (violations.isEmpty()){
//            LOGGER.log(Level.INFO, "validation of user is ok. user is valid"+'\n');
//        } else {
//            LOGGER.log(Level.INFO, "validation of user is ok. user is invalid"+'\n');
//        }

        return dao.update(user);

    }

}
